import React, { useEffect, useState } from 'react';
import { Button, message, Modal } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import PlanInfoForm from './components/PlanInfoForm';
import { fetchPlanData, savePlanData } from './service';
import { PlanInfo, PageState } from './types';
import styles from './index.less';

const initialState: PageState = {
  planInfo: {
    systemName: '',
    implementationTime: '',
    isReporting: true,
    contactPerson: '',
    content: '',
    businessImpact: '',
    otherNotes: ''
  },
  loading: false,
  submitting: false
};

const ProductionPlanningPage: React.FC = () => {
  const [state, setState] = useState<PageState>(initialState);

  // 初始化获取数据
  useEffect(() => {
    loadPlanData();
  }, []);

  // 加载投产规划数据
  const loadPlanData = async () => {
    setState(prev => ({ ...prev, loading: true }));
    try {
      const response = await fetchPlanData();
      if (response.success && response.data) {
        const planInfo: PlanInfo = {
          systemName: response.data.systemName || '',
          implementationTime: response.data.implementationTime || '',
          isReporting: response.data.isReporting || true,
          contactPerson: response.data.contactPerson || '',
          content: response.data.content || '',
          businessImpact: response.data.businessImpact || '',
          otherNotes: response.data.otherNotes || ''
        };
        
        setState(prev => ({ 
          ...prev, 
          planInfo,
          loading: false 
        }));
      } else {
        throw new Error(response.message || '获取数据失败');
      }
    } catch (error) {
      console.error('加载投产规划数据失败:', error);
      message.error('加载投产规划数据失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 处理关闭页面
  const handleClose = () => {
    Modal.confirm({
      title: '确认关闭',
      content: '关闭页面后，未保存的内容将丢失，是否确认关闭？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 这里可以添加关闭页面的逻辑，如跳转路由
        console.log('关闭页面');
      }
    });
  };

  // 处理表单字段变化
  const handleFormChange = (changedValues: Partial<PlanInfo>) => {
    setState(prev => ({
      ...prev,
      planInfo: {
        ...prev.planInfo,
        ...changedValues
      }
    }));
  };

  // 处理保存
  const handleSave = async () => {
    // 简单的表单验证
    const { planInfo } = state;
    if (!planInfo.implementationTime || !planInfo.content || !planInfo.businessImpact) {
      return message.error('请填写必填项');
    }

    setState(prev => ({ ...prev, submitting: true }));
    try {
      const result = await savePlanData(planInfo);
      if (result.success) {
        message.success('保存成功');
      } else {
        message.error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    } finally {
      setState(prev => ({ ...prev, submitting: false }));
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h2 className={styles.title}>重要业务系统投产规划信息汇总</h2>
        <Button 
          icon={<CloseOutlined />}
          className={styles.closeButton}
          onClick={handleClose}
        />
      </div>
      
      <div className={styles.content}>
        <PlanInfoForm 
          planInfo={state.planInfo}
          onChange={handleFormChange}
          loading={state.loading}
        />
      </div>
      
      <div className={styles.footer}>
        <Button
          onClick={handleClose}
        >
          关闭
        </Button>
        <Button
          type="primary"
          loading={state.submitting}
          onClick={handleSave}
        >
          保存
        </Button>
      </div>
    </div>
  );
};

export default ProductionPlanningPage;
